package com.cosmosource.core.utils;

import cn.hutool.core.codec.Base64;

/**
 * @author mahe
 * @date 2022/3/2 11:01
 */
public class Base64Util {

    private static final byte[] ENCODING_TABLE = {
            (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
            (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J',
            (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
            (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
            (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
            (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
            (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
            (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
            (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
            (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
            (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2',
            (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
            (byte) '8', (byte) '9', (byte) '+', (byte) '/'
    };
    private static final byte[] DECODING_TABLE;

    public static final int ONE_HUNDREN_TWENTY_EIGHT = 128;

    public static final char UPPER_CASE_A = 'A';

    public static final char UPPER_CASE_Z = 'Z';

    public static final char LOW_CASE_A = 'a';

    public static final char LOW_CASE_Z = 'z';

    public static final char ZERO = '0';

    public static final char NINE = '9';
    public static final int THREE = 3;
    public static final int FOUR = 4;

    static {
        DECODING_TABLE = new byte[128];
        for (int i = 0; i < ONE_HUNDREN_TWENTY_EIGHT; i++) {
            DECODING_TABLE[i] = (byte) -1;
        }
        for (int i = UPPER_CASE_A; i <= UPPER_CASE_Z; i++) {
            DECODING_TABLE[i] = (byte) (i - 'A');
        }
        for (int i = LOW_CASE_A; i <= LOW_CASE_Z; i++) {
            DECODING_TABLE[i] = (byte) (i - 'a' + 26);
        }
        for (int i = ZERO; i <= NINE; i++) {
            DECODING_TABLE[i] = (byte) (i - '0' + 52);
        }
        DECODING_TABLE['+'] = 62;
        DECODING_TABLE['/'] = 63;
    }

    private static byte[] encode(byte[] data, int offset) {
        byte[] bytes;
        int realCount = data.length - offset;
        int modulus = realCount % 3;
        if (modulus == 0) {
            bytes = new byte[(4 * realCount) / 3];
        } else {
            bytes = new byte[4 * ((realCount / 3) + 1)];
        }
        int dataLength = (data.length - modulus);
        int a1;
        int a2;
        int a3;
        for (int i = offset, j = 0; i < dataLength; i += THREE, j += FOUR) {
            a1 = data[i] & 0xff;
            a2 = data[i + 1] & 0xff;
            a3 = data[i + 2] & 0xff;
            bytes[j] = ENCODING_TABLE[(a1 >>> 2) & 0x3f];
            bytes[j + 1] = ENCODING_TABLE[((a1 << 4) | (a2 >>> 4)) & 0x3f];
            bytes[j + 2] = ENCODING_TABLE[((a2 << 2) | (a3 >>> 6)) & 0x3f];
            bytes[j + 3] = ENCODING_TABLE[a3 & 0x3f];
        }
        int b1;
        int b2;
        int b3;
        int d1;
        int d2;
        switch (modulus) {
            /* nothing left to do */
            case 0:
                break;
            case 1:
                d1 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = (d1 << 4) & 0x3f;
                bytes[bytes.length - 4] = ENCODING_TABLE[b1];
                bytes[bytes.length - 3] = ENCODING_TABLE[b2];
                bytes[bytes.length - 2] = (byte) '=';
                bytes[bytes.length - 1] = (byte) '=';
                break;
            case 2:
                d1 = data[data.length - 2] & 0xff;
                d2 = data[data.length - 1] & 0xff;
                b1 = (d1 >>> 2) & 0x3f;
                b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
                b3 = (d2 << 2) & 0x3f;
                bytes[bytes.length - 4] = ENCODING_TABLE[b1];
                bytes[bytes.length - 3] = ENCODING_TABLE[b2];
                bytes[bytes.length - 2] = ENCODING_TABLE[b3];
                bytes[bytes.length - 1] = (byte) '=';
                break;
            default:
                break;
        }
        return bytes;
    }

    /**
     * 加密
     * 将明文字符串加密成utf-8字符集的加密字符串
     * @param data
     * @return
     * @throws Exception
     */
    public static String encodeToUtf8(String data) throws Exception {
        return encode(data, "UTF-8");
    }

    private static String encode(String data, String charset) throws Exception {
        if (data == null || data.length() == 0) {
            return data;
        }
        byte[] dataBytes = new String(data.getBytes(), getEncoding(data)).getBytes(charset);
        byte[] result = encode(dataBytes, 0);
        StringBuffer sb = new StringBuffer(result.length);
        for (int i = 0; i < result.length; i++) {
            sb.append((char) result[i]);
        }
        return sb.toString();
    }

    /**
     * 解密
     * 将unicode字符集的加密字符串，解码成utf-8字符集的明文字符串
     * @param data
     * @return
     * @throws Exception
     */
    public static String decodeUnicodeToUtf8(String data) throws Exception {
        if (data == null || data.length() == 0) {
            return data;
        }
        byte[] decodeByte = Base64.decode(data);
        if(decodeByte == null){
            return data;
        }
        byte[] bytes = new String(decodeByte, "UTF-8").getBytes("UTF-8");
        return new String(bytes, "UTF-8");
    }

    /**
     * 判断字符编码
     * @param str
     * @return
     */
    private static String getEncoding(String str) {
        String encode = "Unicode";
        try {
            if (str.equals(new String(str.getBytes(encode)))) {
                String s = encode;
                return s;
            }
        } catch (Exception exception) {
        }
        encode = "ISO-8859-1";
        try {
            if (str.equals(new String(str.getBytes(encode)))) {
                String s1 = encode;
                return s1;
            }
        } catch (Exception exception1) {
        }
        encode = "UTF-8";
        try {
            if (str.equals(new String(str.getBytes(encode)))) {
                String s2 = encode;
                return s2;
            }
        } catch (Exception exception2) {
        }
        encode = "GBK";
        try {
            if (str.equals(new String(str.getBytes(encode)))) {
                String s3 = encode;
                return s3;
            }
        } catch (Exception exception3) {
        }
        return "未识别的字符集";
    }
}
